package com.aliang.clickhouseautoconfig.core;


import com.aliang.clickhouseautoconfig.pool.ClickhousePool;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ClickhouseClient {

    private ClickhousePool clickhousePool;

    public ClickhousePool getClickhousePool() {
        return clickhousePool;
    }

    public void setClickhousePool(ClickhousePool clickhousePool) {
        this.clickhousePool = clickhousePool;
    }

    public List<String[]> executeQuery(String sql) {
        final Connection conn = getClickhousePool().getConnection();
        List<String[]> allData = new ArrayList<>();
        try (PreparedStatement preparedStatement = conn.prepareStatement(sql);
             ResultSet rs = preparedStatement.executeQuery()) {
            java.sql.ResultSetMetaData rsmd = rs.getMetaData();
            // 列数
            int columnCount = rsmd.getColumnCount();
            //封装字段名
            String[] title = new String[columnCount];
            for (int i = 1; i <= columnCount; i++) {
                title[i - 1] = rsmd.getColumnName(i);
            }
            allData.add(title);
            while (rs.next()) {
                String[] rowData = new String[columnCount];
                for (int j = 1; j <= columnCount; j++) {
                    //根据字段名获取数据，确保数据匹配字段
                    rowData[j - 1] = rs.getString(title[j - 1]);
                }
                System.out.println(Arrays.toString(rowData));
                allData.add(rowData);
            }
            System.out.println(allData);
            return allData;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            clickhousePool.releaseConnection();
        }
        return allData;
    }
}
